import axios from "axios";
import qs from "qs";
import { AxiosCanceler } from "./helper/axiosCancel";
import { logout } from "@/utils/system/system";

// let errMsg = ''

const baseURL = "https://cnsuzwhp6162894.eaton.ad.etn.com/api/v1/";
const useMock = true;

const axiosCanceler = new AxiosCanceler();

const transformRequestFunc = function (data) {
  // 对 data 进行任意转换处理
  // `transformRequest` 允许在向服务器发送前，修改请求数据
  // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 后面数组中的函数必须返回一个字符串，或 ArrayBuffer，或 Stream
  if (data instanceof FormData) {
    return data;
  }
  return qs.stringify(data);
};
// create an axios instance
const service = axios.create({
  baseURL: baseURL, // url = base url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 100000000, // request timeout
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
});
//axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
// request interceptor
service.interceptors.request.use(
  (config) => {
    // * 将当前请求添加到 pending 中
    axiosCanceler.addPending(config);
    config.headers = {
      ...config.headers,
    };
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  async (response) => {
    if (response.status >= 200 && response.status < 300) {
      let res = response.data;
      return res;
    }
    let data = null;
    try {
      data = await response.clone().json();
    } catch (e) {
      console.log(e);
    }
    const errorObj = { response, data };
    throw errorObj;
  },
  (error) => {
    return new Promise((resolve, reject) => {
      const { response } = error;
      if (response && response.status) {
        if (response.status === 401) {
          logout();
          return reject({ success: false, msg: "您的登录信息已经失效" });
        } else if (response.status === 403 || response.status === 400) {
          return reject({ success: false, msg: "您没有权限进行当前的操作" });
        } else if (response.status === 404) {
          return reject({ success: false, msg: "链接未找到" });
        } else {
          return reject({ success: false, msg: "请求错误" });
        }
      } else if (!response) {
        return reject({
          success: false,
          msg: "您的网络发生异常，无法连接服务器",
        });
      }
      return reject(error);
    });
  }
);

export const MockResult = {
  success(data) {
    return { success: true, code: 200, data, msg: "处理成功" };
  },
  fail(code, data) {
    return { success: false, code, data, msg: "error" };
  },
};

const request = (params) => {
  if (useMock && params.mock && params.mock.useMock) {
    if (params.mock.data && typeof params.mock.data === "function") {
      return new Promise((resolve, reject) => {
        let mockData = params.mock.data();
        if (mockData.success && mockData.code === 200) {
          console.info(
            "Mock Http Request:",
            params.url,
            params.method,
            mockData
          );
          setTimeout(() => {
            resolve(mockData);
          }, params.mock.delay || 1000);
        } else {
          console.error(
            "Mock Http Request:",
            params.url,
            params.method,
            mockData
          );
          reject({ response: { data: mockData, status: 200 } });
        }
      });
    }
    return new Promise((resolve, reject) => {
      let mockData = params.mock.data;
      if (mockData.success && mockData.code === 200) {
        console.info("Mock Http Request:", params.url, params.method, mockData);
        setTimeout(() => {
          resolve(mockData);
        }, params.mock.delay || 1000);
      } else {
        reject({ response: { data: mockData, status: 200 } });
        console.error(
          "Mock Http Request:",
          params.url,
          params.method,
          mockData
        );
      }
    });
  }
  if (
    !(
      params &&
      params.headers &&
      params.headers["Content-Type"] &&
      params.headers["Content-Type"].indexOf("application/json") >= 0
    )
  ) {
    params.transformRequest = [transformRequestFunc];
  }
  return service(params);
};

export default request;
